{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Jena "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[RDF参考手册](https://www.runoob.com/rdf/rdf-reference.html)   \n",
    "[SPARQL Tutorial](https://jena.apache.org/tutorials/sparql.html)  \n",
    "[SPARQL 1.1 Query Language](https://www.w3.org/TR/sparql11-query/#introduction)  \n",
    "[sparql入门-中文教程](https://blog.csdn.net/minosisterry/article/details/102613785)  \n",
    "docker run -d --rm --name fuseki -p 3030:3030 -e ADMIN_PASSWORD=vincent -v $HOME/fuseki:/fuseki stain/jena-fuseki  \n",
    "http://192.168.214.66:3030/  (上传数据  .nt  .rdf)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 不允许出现空格 \n",
    "# 英文 ()  [] {}\n",
    "# 中英文  ”“ \"\"  ‘’  ''\n",
    "#  & # @ * % / \\ \n",
    "\n",
    "# 属性值中不能包含多个  \"\" \n",
    "# 属性值中不能包含 \\\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\n",
      "Requirement already satisfied: SPARQLWrapper in c:\\programdata\\anaconda3\\lib\\site-packages (1.8.5)\n",
      "Requirement already satisfied: rdflib>=4.0 in c:\\programdata\\anaconda3\\lib\\site-packages (from SPARQLWrapper) (5.0.0)\n",
      "Requirement already satisfied: pyparsing in c:\\programdata\\anaconda3\\lib\\site-packages (from rdflib>=4.0->SPARQLWrapper) (2.3.0)\n",
      "Requirement already satisfied: isodate in c:\\programdata\\anaconda3\\lib\\site-packages (from rdflib>=4.0->SPARQLWrapper) (0.6.0)\n",
      "Requirement already satisfied: six in c:\\programdata\\anaconda3\\lib\\site-packages (from rdflib>=4.0->SPARQLWrapper) (1.12.0)\n"
     ]
    }
   ],
   "source": [
    "# 安装 SPARQLWrapper 包\n",
    "! pip install SPARQLWrapper  -i  https://pypi.tuna.tsinghua.edu.cn/simple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json \n",
    "import os \n",
    "from SPARQLWrapper import SPARQLWrapper, JSON"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### 数据库查询"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建 query 对象。 \"http://192.168.214.66:3030/dataset_01\"  服务器 【IP:端口/数据库名称】\n",
    "query = SPARQLWrapper(\"http://192.168.214.66:3030/dataset_01/query\")\n",
    "# 查询结果返回格式 \n",
    "query.setReturnFormat(JSON)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \".1\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \".1\": {\n",
      "          \"datatype\": \"http://www.w3.org/2001/XMLSchema#integer\",\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"1\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询数据库中 图数量\n",
    "sparql_code = \"\"\"\n",
    "select COUNT(distinct ?g)\n",
    "where {graph ?g{?s ?p ?o}}\n",
    "\"\"\"\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"g\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \"g\": {\n",
      "          \"type\": \"uri\",\n",
      "          \"value\": \"http://192.168.214.66:3030/dataset_01/data/demo_01\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询数据库中 图名称 \n",
    "sparql_code = \"\"\"\n",
    "select distinct ?g\n",
    "where {graph ?g{?s ?p ?o}}\n",
    "\"\"\"\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"subject\",\n",
      "      \"predicate\",\n",
      "      \"object\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": []\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询数据库中 图中内容 \n",
    "sparql_code = \"\"\"\n",
    "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
    "\n",
    "SELECT ?subject ?predicate ?object\n",
    "from <http://192.168.214.66:3030/demo_01/data/demo_01>\n",
    "WHERE {\n",
    "  ?subject ?predicate ?object\n",
    "}\n",
    "LIMIT 25\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "demo_01.rdf\n",
    "\n",
    "    <rdf:RDF\n",
    "      xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'   \n",
    "      xmlns:Relation='http://www.w3.org/2001/relation#'\n",
    "      > <!--  RDF标准   -->\n",
    "\n",
    "      <rdf:Description  about=\"贾代善\">\n",
    "        <Relation:儿子>贾赦</Relation:儿子>\n",
    "        <Relation:儿子>贾政</Relation:儿子>\t\n",
    "        <Relation:妻>贾母</Relation:妻>\n",
    "        <Relation:妾>老姨奶奶</Relation:妾>\n",
    "      </rdf:Description >\n",
    "\n",
    "      <rdf:Description  about=\"贾赦\">\n",
    "        <Relation:儿子>贾琮</Relation:儿子>\n",
    "        <Relation:妻>邢夫人</Relation:妻>\n",
    "        <Relation:妾>翠云</Relation:妾>\n",
    "      </rdf:Description >\n",
    "\n",
    "      <rdf:Description  about=\"贾琮\">\n",
    "        <Relation:乳母>贾琮奶妈</Relation:乳母>\n",
    "      </rdf:Description >\n",
    "\n",
    "    </rdf:RDF>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "GRAPH = '<http://192.168.214.66:3030/dataset_01/data/demo_01>'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"object\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \"object\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"贾政\"\n",
      "        }\n",
      "      },\n",
      "      {\n",
      "        \"object\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"贾赦\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询  贾代善的儿子\n",
    "sparql_code = \"\"\"\n",
    "PREFIX Subject: <http://192.168.214.66:3030/dataset_01/>\n",
    "PREFIX Relation: <http://www.w3.org/2001/relation#>\n",
    "\n",
    "SELECT ?object\n",
    "from GRAPH\n",
    "WHERE {\n",
    "  Subject:贾代善 Relation:儿子 ?object\n",
    "}\n",
    "\n",
    "\"\"\".replace('GRAPH', GRAPH)\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"object\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \"object\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"老姨奶奶\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询  贾政父亲的妾\n",
    "sparql_code = \"\"\"\n",
    "PREFIX Subject: <http://192.168.214.66:3030/dataset_01/>\n",
    "PREFIX Relation: <http://www.w3.org/2001/relation#>\n",
    "\n",
    "SELECT ?object\n",
    "from GRAPH\n",
    "WHERE {\n",
    "  ?x Relation:儿子 \"贾政\" .\n",
    "  ?x Relation:妾 ?object  \n",
    "}\n",
    "\n",
    "\"\"\".replace('GRAPH', GRAPH)\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"object\",\n",
      "      \"x\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \"x\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"贾政\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询  贾代善的儿子（名字中带有“政”）  【FILTER regex(?x, \"政\")  正则过滤】\n",
    "sparql_code = \"\"\"\n",
    "PREFIX Subject: <http://192.168.214.66:3030/dataset_01/>\n",
    "PREFIX Relation: <http://www.w3.org/2001/relation#>\n",
    "\n",
    "SELECT ?object ?x\n",
    "from GRAPH\n",
    "WHERE {\n",
    "  Subject:贾代善 Relation:儿子 ?x .\n",
    "  FILTER regex(?x, \"政\").\n",
    "}\n",
    "\n",
    "\"\"\".replace('GRAPH', GRAPH)\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"object\",\n",
      "      \"x\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \"x\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"贾政\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询  贾代善的儿子（名字中带有“政”）  【FILTER regex(?x, \"政\")  正则过滤】\n",
    "sparql_code = \"\"\"\n",
    "PREFIX Subject: <http://192.168.214.66:3030/dataset_01/>\n",
    "PREFIX Relation: <http://www.w3.org/2001/relation#>\n",
    "\n",
    "SELECT ?object ?x\n",
    "from GRAPH\n",
    "WHERE {\n",
    "  Subject:贾代善 Relation:儿子 ?x .\n",
    "  FILTER regex(?x, \"政\").\n",
    "}\n",
    "\n",
    "\"\"\".replace('GRAPH', GRAPH)\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"person\",\n",
      "      \"wife\",\n",
      "      \"daught\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \"person\": {\n",
      "          \"type\": \"uri\",\n",
      "          \"value\": \"http://192.168.214.66:3030/dataset_01/贾赦\"\n",
      "        },\n",
      "        \"wife\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"邢夫人\"\n",
      "        }\n",
      "      },\n",
      "      {\n",
      "        \"person\": {\n",
      "          \"type\": \"uri\",\n",
      "          \"value\": \"http://192.168.214.66:3030/dataset_01/贾代善\"\n",
      "        },\n",
      "        \"wife\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"贾母\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询  XX 的 妻子、女儿  【OPTIONAL { ?person Relation:女 ?daught }  可选项】\n",
    "sparql_code = \"\"\"\n",
    "PREFIX Subject: <http://192.168.214.66:3030/dataset_01/>\n",
    "PREFIX Relation: <http://www.w3.org/2001/relation#>\n",
    "\n",
    "SELECT ?person ?wife ?daught\n",
    "from GRAPH\n",
    "WHERE {\n",
    "  ?person Relation:妻 ?wife .\n",
    "  OPTIONAL { ?person Relation:女 ?daught }\n",
    "}\n",
    "\n",
    "\"\"\".replace('GRAPH', GRAPH)\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"x\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \"x\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"翠云\"\n",
      "        }\n",
      "      },\n",
      "      {\n",
      "        \"x\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"老姨奶奶\"\n",
      "        }\n",
      "      },\n",
      "      {\n",
      "        \"x\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"贾母\"\n",
      "        }\n",
      "      },\n",
      "      {\n",
      "        \"x\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"邢夫人\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询  为 妻或妾  【UNION {[] Relation:妻 ?x} UNION {[] Relation:妾 ?x} 联合查询】\n",
    "sparql_code = \"\"\"\n",
    "PREFIX Subject: <http://192.168.214.66:3030/dataset_01/>\n",
    "PREFIX Relation: <http://www.w3.org/2001/relation#>\n",
    "\n",
    "SELECT ?x\n",
    "from GRAPH\n",
    "WHERE {\n",
    "  {[] Relation:妻 ?x} UNION {[] Relation:妾 ?x}\n",
    "}\n",
    "ORDER BY ?x\n",
    "\"\"\".replace('GRAPH', GRAPH)\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"x\",\n",
      "      \"y\",\n",
      "      \"object\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": []\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 查询 贾代善 的妻子的女儿 【查询失败， rdf文件中Object暂时无法与Subject连通】\n",
    "sparql_code = \"\"\"\n",
    "PREFIX Subject: <http://192.168.214.66:3030/dataset_01/>\n",
    "PREFIX Relation: <http://www.w3.org/2001/relation#>\n",
    "\n",
    "SELECT ?x ?y ?object\n",
    "from GRAPH\n",
    "WHERE {\n",
    "\tSubject:贾代善 Relation:妻 ?y .\n",
    "  \t ?y  Relation:女 ?object  \n",
    "}\n",
    "\n",
    "\"\"\".replace('GRAPH', GRAPH)\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "demo_03.nt  \n",
    "\n",
    "    <file://demo_4.nt/entity#person/57607> <file://demo_4.nt/attribute#personBiography> \"香港演员、导演。祖籍浙江宁波，1962年6月22日生于香港，他是香港最为重要的喜剧片演员与编导之一。\"  .\n",
    "    <file://demo_4.nt/entity#person/57607> <file://demo_4.nt/attribute#personEnglishName> \"Stephen Chow\" .\n",
    "    <file://demo_4.nt/entity#person/57607> <file://demo_4.nt/attribute#personName> \"周星驰\" .\n",
    "    <file://demo_4.nt/entity#person/57607> <file://demo_4.nt/attribute#personBirthDay> \"1962-06-22\" .\n",
    "    <file://demo_4.nt/entity#person/57607> <file://demo_4.nt/attribute#personBirthPlace> \"Hong Kong\" .\n",
    "    <file://demo_4.nt/entity#person/57607> <file://demo_4.nt/attribute#type> 'Person' .\n",
    "    <file://demo_4.nt/entity#person/57607> <file://demo_4.nt/attribute#hasActedIn> <file://demo_4.nt/entity#movie/9470> .\n",
    "    <file://demo_4.nt/entity#person/57607> <file://demo_4.nt/attribute#hasActedIn> <file://demo_4.nt/entity#movie/11471> .\n",
    "    <file://demo_4.nt/entity#movie/9470> <file://demo_4.nt/attribute#movieRating> \"7.2E0\"^^<http://www.w3.org/2001/XMLSchema#double> .\n",
    "    <file://demo_4.nt/entity#movie/9470> <file://demo_4.nt/attribute#movieIntroduction> \"1940年代的上海，自小受尽欺辱的街头混混阿星（周星驰）为了能出人头地，可谓窥见机会的缝隙就往里钻，今次他盯上行动日益猖獗的黑道势力“斧头帮”，想借之大名成就大业。\" .\n",
    "    <file://demo_4.nt/entity#movie/9470> <file://demo_4.nt/attribute#movieTitle> \"功夫\" .\n",
    "    <file://demo_4.nt/entity#movie/9470> <file://demo_4.nt/attribute#movieReleaseDate> \"2004-02-10\" .\n",
    "    <file://demo_4.nt/entity#movie/9470> <file://demo_4.nt/attribute#type> <file://demo_4.nt/attribute#Movie> .\n",
    "    <file://demo_4.nt/entity#movie/11471> <file://demo_4.nt/attribute#movieRating> \"7.3\" .\n",
    "    <file://demo_4.nt/entity#movie/11471> <file://demo_4.nt/attribute#movieIntroduction> \"香港某个国际伪钞集团重要分子宋子豪（狄龙）和Mark（周润发）情同手足.\" .\n",
    "    <file://demo_4.nt/entity#movie/11471> <file://demo_4.nt/attribute#movieTitle> \"英雄本色\" .\n",
    "    <file://demo_4.nt/entity#movie/11471> <file://demo_4.nt/attribute#movieReleaseDate> \"1986-08-02\" .\n",
    "    <file://demo_4.nt/entity#movie/11471> <file://demo_4.nt/attribute#type> <file://demo_4.nt/attribute#Movie> .\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "GRAPH = '<http://192.168.214.66:3030/dataset_01/data/demo_03>'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"subject\",\n",
      "      \"name\",\n",
      "      \"object\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \"name\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"功夫\"\n",
      "        },\n",
      "        \"object\": {\n",
      "          \"type\": \"uri\",\n",
      "          \"value\": \"file://demo_4.nt/entity#movie/9470\"\n",
      "        },\n",
      "        \"subject\": {\n",
      "          \"type\": \"uri\",\n",
      "          \"value\": \"file://demo_4.nt/entity#person/57607\"\n",
      "        }\n",
      "      },\n",
      "      {\n",
      "        \"name\": {\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"英雄本色\"\n",
      "        },\n",
      "        \"object\": {\n",
      "          \"type\": \"uri\",\n",
      "          \"value\": \"file://demo_4.nt/entity#movie/11471\"\n",
      "        },\n",
      "        \"subject\": {\n",
      "          \"type\": \"uri\",\n",
      "          \"value\": \"file://demo_4.nt/entity#person/57607\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 周星驰  ——》 参演电影  ——》名称\n",
    "sparql_code = \"\"\"\n",
    "PREFIX :<file://demo_4.nt/attribute#>\n",
    "\n",
    "SELECT ?subject ?name ?object\n",
    "from GRAPH\n",
    "WHERE {\n",
    "  ?subject :type 'Person'.\n",
    "  ?subject :personName '周星驰'.\n",
    "  ?subject :hasActedIn ?object.\n",
    "  ?object :movieTitle ?name\n",
    "}\n",
    "\"\"\".replace('GRAPH', GRAPH)\n",
    "\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"name\",\n",
      "      \"rating\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": []\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 周星驰参演的电影(评分大于7)有哪些？\n",
    "sparql_code = \"\"\"\n",
    "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n",
    "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
    "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n",
    "PREFIX : <http://www.kgdemo.com#>\n",
    "\n",
    "SELECT ?name ?rating \n",
    "WHERE {\n",
    "  ?subject rdf:type :Person.\n",
    "  ?subject :personName '周星驰'.\n",
    "  ?subject :hasActedIn ?object.\n",
    "  ?object :movieTitle ?name.\n",
    "  ?object :movieRating ?rating.  \n",
    "  FILTER (?rating > 7)\n",
    "}\n",
    "LIMIT 3\n",
    "\"\"\"\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"predicate\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": []\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# predicate 值 \n",
    "sparql_code = \"\"\"\n",
    "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n",
    "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
    "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n",
    "PREFIX : <http://www.kgdemo.com#>\n",
    "\n",
    "SELECT distinct ?predicate \n",
    "WHERE {\n",
    "  ?subject ?predicate ?object\n",
    "}\n",
    "LIMIT 10\n",
    "\"\"\"\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \".1\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": [\n",
      "      {\n",
      "        \".1\": {\n",
      "          \"datatype\": \"http://www.w3.org/2001/XMLSchema#integer\",\n",
      "          \"type\": \"literal\",\n",
      "          \"value\": \"0\"\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 所有实体 subject 数量 \n",
    "sparql_code = \"\"\"\n",
    "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n",
    "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
    "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n",
    "PREFIX : <http://www.kgdemo.com#>\n",
    "\n",
    "SELECT Count(distinct ?subject)\n",
    "WHERE {\n",
    "  ?subject ?predicate ?object\n",
    "}\n",
    "LIMIT 10\n",
    "\"\"\"\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"name\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": []\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 所有的演员名称 \n",
    "sparql_code = \"\"\"\n",
    "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n",
    "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
    "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n",
    "PREFIX : <http://www.kgdemo.com#>\n",
    "\n",
    "SELECT ?name \n",
    "WHERE {\n",
    "  ?subject rdf:type :Person.\n",
    "  ?subject :personName ?name\n",
    "}\n",
    "LIMIT 5\n",
    "\"\"\"\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"name\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": []\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 所有的电影名称 \n",
    "sparql_code = \"\"\"\n",
    "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n",
    "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
    "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n",
    "PREFIX : <http://www.kgdemo.com#>\n",
    "\n",
    "SELECT ?name \n",
    "WHERE {\n",
    "  ?subject rdf:type :Person.\n",
    "  ?subject :hasActedIn ?object.\n",
    "  ?object :movieTitle ?name\n",
    "}\n",
    "LIMIT 5\n",
    "\"\"\"\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"head\": {\n",
      "    \"vars\": [\n",
      "      \"subject\",\n",
      "      \"o\",\n",
      "      \"a\",\n",
      "      \"b\"\n",
      "    ]\n",
      "  },\n",
      "  \"results\": {\n",
      "    \"bindings\": []\n",
      "  }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# 所有的电影名称 \n",
    "sparql_code = \"\"\"\n",
    "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n",
    "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
    "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n",
    "PREFIX : <file://attribute#> \n",
    "PREFIX Entity: <file://entity#> \n",
    "\n",
    "SELECT ?subject ?o ?a ?b\n",
    "from  <http://192.168.214.66:3030/dataset_01/data/demo_13>\n",
    "WHERE {\n",
    "  Entity:黄宗泽 ?a ?b\n",
    "}\n",
    "LIMIT 50\n",
    "\"\"\"\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "60.6 ms ± 13.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit raw_response = query.query().convert()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 所有的电影名称 \n",
    "sparql_code = \"\"\"\n",
    "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n",
    "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n",
    "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n",
    "PREFIX : <file://attribute#> \n",
    "PREFIX Entity: <file://entity#> \n",
    "\n",
    "SELECT distinct ?x\n",
    "from  <http://localhost:3030/dataset_01/data/ownthink_02>\n",
    "WHERE {\n",
    "  Entity:刘德华 ?x ?y\n",
    "}\n",
    "\"\"\"\n",
    "query.setQuery(sparql_code)\n",
    "raw_response = query.query().convert()\n",
    "\n",
    "# print(json.dumps(raw_response, ensure_ascii=False, sort_keys=True, indent=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "65.9 ms ± 3.35 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit raw_response = query.query().convert()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'head': {'vars': ['x']}, 'results': {'bindings': []}}"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "raw_response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
